<?php

namespace app\api\controller;

use app\api\server\Goods;
use app\api\server\User as ServerUser;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Wechat;
use app\common\model\Area;
use app\common\model\Bank;
use app\common\model\User as ModelUser;
use app\common\model\user\Apply;
use app\common\model\user\Collect;
use app\common\model\user\Withdrawal;
use app\common\model\UserGroup;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'miniLogin',  'changemobile'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $userInfo = ModelUser::get($this->auth->id, ['inviter']);
        $this->success('', $userInfo);
    }

    /**
     * 会员登录
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * @Author LK
     * @date: 2024-01-15 
     * @ApiTitle (授权手机号)
     * @ApiMethod (POST)
     * @ApiParams (name="phoneCode", type="string", required=true, sample="", description="手机code")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function auth_phone()
    {
        $params = $this->request->param();
        extract($params);
        try {
            $wechat = new Wechat('wxMiniProgram');
            $res = $wechat->getPhone($phoneCode);
            if ($res['errcode'] == 0) {
                $phone = $res['phone_info'];
            } else {
                exception('失败:' . $res['errmsg']);
            }
            // 分参
            $user = \app\common\model\User::get($this->auth->id);
            $user->mobile = $phone['phoneNumber'];
            $user->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }
    /**
     * @Author LK
     * @ApiTitle (微信小程序登录)
     * @ApiMethod (POST)
     * @ApiParams (name="code", type="integer", required=true, sample="", description="登录code")
     * @ApiParams (name="phoneCode", type="string", required=true, sample="", description="手机code")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function miniLogin()
    {
        $params = $this->request->param();
        extract($params);
        // 入参
        if (empty($code)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            $wechat = new Wechat('wxMiniProgram');
            $decryptSession = $wechat->code($code);
            if (!isset($decryptSession['session_key'])) {
                exception($decryptSession['errmsg']);
            }
            if (!$decryptSession || !isset($decryptSession['openid'])) {
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptSession['openid'])) {
                exception('code错误,请重试!');
            }
            $res = $wechat->getPhone($phoneCode);
            if ($res['errcode'] == 0) {
                $phone = $res['phone_info'];
            } else {
                exception('失败:' . $res['errmsg']);
            }
            // 分参
            $user = \app\common\model\User::get([
                'openid'   => $decryptSession['openid'],
            ]);

            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                // 直接登陆
                $result = $this->auth->direct($user->id, $decryptSession['openid']);
            } else {
                $decryptSession['mobile'] = $phone['phoneNumber'];
                $result = $this->auth->oauthRegister($decryptSession);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!' . $this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($avatar) {
            $user->avatar = $avatar;
        }
        if ($username) {

            $user->username = $username;
        }
        if ($nickname) {

            $user->nickname = $nickname;
        }
        $user->save();
        $this->success();
    }


    /**
     * 修改手机号
     *@ApiInternal
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }



    /**
     * 重置密码
     *@ApiInternal
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (银行卡管理)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function my_bank()
    {
        $list = Bank::where('user_id', $this->auth->id)->paginate();
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (获取默认银行卡)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function get_bank()
    {
        $list = Bank::get(['is_default' => 1, 'user_id' => $this->auth->id]);
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (设置默认银行卡)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function set_default_bank()
    {
        $params = request()->param();
        extract($params);
        $uid = $this->auth->id;
        Bank::where('user_id', $uid)->update(['is_default' => 0]);
        Bank::where('user_id', $uid)->where('id', $id)->update(['is_default' => 1]);
        $this->success('成功');
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (银行卡详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function bank_info()
    {
        $params = request()->param();
        extract($params);
        $list = Bank::get($id);
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (添加银行卡)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="name", type="string", required=true, sample="", description="开户人")
     * @ApiParams (name="bank", type="string", required=true, sample="", description="开户行")
     * @ApiParams (name="branch", type="string", required=true, sample="", description="开户支行")
     * @ApiParams (name="account", type="string", required=true, sample="", description="开户账号")
     * @ApiParams (name="is_default", type="string", required=true, sample="", description="0=不默认,1=默认")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function add_edit_bank()
    {
        $params = request()->param();
        extract($params);
        $uid = $this->auth->id;
        $params['user_id'] = $uid;
        if ($params['is_default'] == 1) {
            Bank::update(['is_default' => 0], ['user_id' => $uid]);
        }
        if (isset($id) && $id) {
            $res = Bank::update($params, ['id' => $id]);
        } else {
            $res = Bank::create($params, true);
        }
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (删除银行卡)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function del_bank()
    {
        $params = request()->param();
        extract($params);
        $res = Bank::where('id', $id)->delete();
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }

    /**
     * @Author LK
     * @ApiTitle (提现)
     * @ApiMethod (POST)
     * @ApiParams (name="money", type="integer", required=true, sample="", description="提现金额")
     * @ApiParams (name="type", type="integer", required=true, sample="", description="提现方式:1=微信提现,2=支付宝,3=银行卡")
     * @ApiParams (name="account", type="string", required=false, sample="", description="账号")
     * @ApiParams (name="bank_id", type="string", required=false, sample="", description="银行卡id")
     * @ApiParams (name="mark", type="string", required=false, sample="", description="备注")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function withdrawal()
    {
        $post = $this->request->post();
        $user = ModelUser::get($this->auth->id);
        extract($post);
        $validate = validate('user.Withdrawal'); //使用助手函数
        if ($type == 1) {
            $scene = 'wechat';
        } elseif ($type == 2) {
            $scene = 'alipay';
        } elseif ($type == 3) {
            $scene = 'bank';
        }
        $result = $validate->scene($scene)->check($post);
        if (!$result) {
            $this->error($validate->getError());
        }
        $withdrawal_commission = config('site.withdrawal_commission');
        if ($withdrawal_commission > 0 && $withdrawal_commission <= 100) {
            $withdrawal_commission_fee = bcdiv($withdrawal_commission, 100, 2);
            $handling_charge = bcmul($money, $withdrawal_commission_fee, 2);
        } else {
            $handling_charge = 0;
        }
        if ($type == 3) {
            $bank = Bank::get($bank_id);
            $post['account'] = $bank->account;
        }
        $post['sn'] = sn('user_withdrawal', 'sn', 'TX');
        $post['user_id'] = $user['id'];
        $post['handling_charge'] = $handling_charge;
        $post['amount_received'] = bcsub($money, $handling_charge, 0);
        $post['type'] = $type;
        Db::startTrans();
        try {
            $tx = new Withdrawal($post);
            $tx->allowField(true)->save();
            ModelUser::money(-$money, $user['id'], '用户提现');
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('申请成功');
    }
    /**
     * @Author LK
     * @ApiTitle (用户提现记录)
     * @ApiMethod (get)
     * @ApiParams (name="state", type="integer", required=true, sample="", description="1=提现中,2=提现成功,3=提现失败")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function withdrawalLog()
    {
        $get = request()->get();
        extract($get);
        $withdrawal = new Withdrawal;

        if ($state != 'all') {
            $withdrawal->where('state', $state);
        }
        $withdrawal->with(['bank']);
        $withdrawal->where('withdrawal.user_id', $this->auth->id);
        $withdrawal->order('createtime desc');
        $list = $withdrawal->field("withdrawal.*,FROM_UNIXTIME(withdrawal.createtime,'%Y-%m-%d') as create_time")->paginate(10);

        $this->success('', $list);
    }

    /**
     * @Author LK
     * @date: 2023-12-26 
     * @ApiTitle (我的收藏)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function user_collect()
    {
        $lists = Collect::with(['goods'])->where('user_id', $this->auth->id)->paginate();
        foreach ($lists as $k => $v) {
            $v->goods->vip_price = Goods::vip_price($v->goods, $this->auth->group_id);
        }
        $this->success('', $lists);
    }

    /**
     * @Author LK
     * @date: 2023-12-28 
     * @ApiTitle (邀请码绑定)
     * @ApiMethod (POST)
     * @ApiParams (name="qr_code", type="integer", required=true, sample="", description="邀请码")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function invitation_code()
    {
        $param = request()->param();
        $param['uid'] = $this->auth->id;
        try {
            ServerUser::binding_relationship($param);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }

    /**
     * @Author LK
     * @date: 2024-01-05 
     * @ApiTitle (省管申请/编辑)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="area_id", type="integer", required=true, sample="", description="省ID")
     * @ApiParams (name="name", type="integer", required=true, sample="", description="姓名")
     * @ApiParams (name="mobile", type="integer", required=true, sample="", description="手机号")
     * @ApiParams (name="business", type="integer", required=true, sample="", description="营业执照")
     * @ApiParams (name="proof", type="integer", required=true, sample="", description="凭证")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function apply()
    {
        $param = request()->param();
        extract($param);
        $uid = $this->auth->id;
        $director = ModelUser::where("find_in_set({$uid},paren_ids)")->where('group_id', 4)->count();
        $member = ModelUser::where("find_in_set({$uid},paren_ids)")->count();
        $group = UserGroup::get(5);
        if ($director < $group['manager_num'] || $member < $group['team_size']) {
            $this->error('申请条件不满足');
        }
        $area = Area::get($area_id);
        $info = Apply::get(['user_id' => $uid]);
        $data = [
            'province' => $area->name,
            'user_id' => $this->auth->id,
            'name' => $name,
            'mobile' => $mobile,
            'business' => $business,
            'proof' => $proof,
            'code' => $area->id,
        ];
        if ($info) {
            Apply::update($data, ['id' => $id], true);
        } else {
            Apply::create($data, true);
        }
        $this->success('成功');
    }
    /**
     * @Author LK
     * @date: 2024-01-09 
     * @ApiTitle (省管申请条件)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function conditions()
    {
        $info = UserGroup::where('id', 5)->field('manager_num,team_size')->find();
        $info->num = ModelUser::where('find_in_set(:id,paren_ids)', ['id' => $this->auth->id])->where('group_id', 5)->count();
        $info->size = ModelUser::where('find_in_set(:id,paren_ids)', ['id' => $this->auth->id])->count();
        $this->success('', $info);
    }

    /**
     * @Author LK
     * @date: 2024-01-05 
     * @ApiTitle (省管申请详情)
     * @ApiMethod (get)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function apply_info()
    {
        $param = request()->param();
        extract($param);
        $uid = $this->auth->id;
        $info = Apply::get(['user_id' => $uid]);
        $this->success('成功', $info);
    }
}
